package cn.xuqiudong.sso.server.service;

import cn.xuqiudong.sso.common.constant.Oauth2Constant;
import cn.xuqiudong.sso.server.session.CodeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 描述:
 *   首页 登录登出的一些操作
 * @author Vic.xu
 * @since 2021-11-03 10:35
 */
@Service
public class IndexService {
    private static Logger logger = LoggerFactory.getLogger(IndexService.class);

    @Resource
    private CodeManager codeManager;


    /**
     * 创建tgt对应的授权码，并重定向到客户端
     * @param redirectUri
     * @param tgt
     * @return
     */
    public String generateCodeAndRedirect(String redirectUri, String tgt) throws UnsupportedEncodingException {
        // 生成授权码
        String code = codeManager.generate(tgt, true, redirectUri);
        String redirect = "redirect:" + authRedirectUri(redirectUri, code);
        logger.debug("创建tgt对应的授权码，并重定向到客户端;redirectUri = {}", redirect);
        return redirect;
    }

    /**
     * 将授权码拼接到回调redirectUri中
     * @param redirectUri
     * @param code
     * @return
     * @throws UnsupportedEncodingException
     */
    private String authRedirectUri(String redirectUri, String code) throws UnsupportedEncodingException {
        StringBuilder sbf = new StringBuilder(redirectUri);
        if (redirectUri.indexOf("?") > -1) {
            sbf.append("&");
        } else {
            sbf.append("?");
        }
        sbf.append(Oauth2Constant.AUTH_CODE).append("=").append(code);
        return URLDecoder.decode(sbf.toString(), "utf-8");
    }

}
